<template>
  <div class="app-main" v-loading="loading">
    <div class="divTmp" v-show="loading"></div>
    <div class="ko-view" v-show="!loading">
      <div class="form-wrapper" id="form-user">
        <div class="user-info-title">{{ $t('personalInfo.info') }}</div>
        <div class="form-group clearfix">
          <div class="user-info-label">{{ $t('personalInfo.user.username') }}</div>
          <div class="pull-left gray user-info-userName">{{ form.username }}</div>
        </div>
        <el-form class="user-form" ref="form" :model="form" :rules="rules" @submit.native.prevent>
          <div class="clearfix">
            <div class="pull-left-tea">
              <div class="form-group clearfix">
                <div class="user-info-label">{{ $t('personalInfo.user.avatar') }}</div>
                <div class="avatar-area clearfix pull-left">
                  <div class="avatar-container pull-left">
                    <img class="avatar" v-if="imageUrl" :src="imageUrl">
                    <img class="avatar" v-else :src="image"/>
                  </div>

                  <!--                el-upload写在form中会自动提交，导致页面自动刷新-->
                  <!--                在form标签中加上@submit.native.prevent-->
                  <el-upload
                      class="pull-left a"
                      action="/api/common/upload"
                      :show-file-list="false"
                      :on-success="handleAvatarSuccess"
                      :before-upload="beforeAvatarUpload"
                      :headers=headers>
                    <button class="button button-red-solid">{{ $t('personalInfo.upload') }}</button>
                    <div class="tip-text">{{ $t('personalInfo.note') }}</div>
                  </el-upload>
                </div>

              </div>
              <div class="form-group clearfix">
                <div class="user-info-label">{{ $t('personalInfo.user.phone') }}</div>
                <div class="label-right">
                  <span>{{ form.phone }}</span>
                  <a class="edit" @click="openDialog('phone')">{{ $t('personalInfo.revisePhone') }}</a>
                </div>
              </div>
              <div class="form-group clearfix">
                <div class="user-info-label">
                  <span>{{ $t('personalInfo.user.email') }}</span>
                </div>
                <div class="label-right">
                  <span>{{ form.email }}</span>
                  <a class="edit" @click="openDialog('email')">{{ $t('personalInfo.reviseEmail') }}</a>
                </div>
              </div>
              <div class="form-group clearfix">
                <div class="user-info-label">
                  <i>*</i>
                  <span>{{ $t('personalInfo.user.name') }}</span>
                </div>
                <el-form-item prop="name" style="margin-bottom: 0">
                  <input name="name" class="text-input valid"
                         style="padding: 0 12px;border: 1px solid #e3e3e9;" v-model="form.name"/>
                </el-form-item>

                <p class="error-tip tip-text">{{ $t('personalInfo.user.nameInfo') }}</p>
              </div>
              <el-form-item class="form-group clearfix" prop="type">
                <div class="user-info-label">{{ $t('personalInfo.user.sex') }}</div>
                <el-radio-group class="radio-group" v-model="radio">
                  <el-radio class="radio-item" :label="1">{{ $t('personalInfo.user.man') }}</el-radio>
                  <el-radio class="radio-item" :label="2">{{ $t('personalInfo.user.lady') }}</el-radio>
                </el-radio-group>
              </el-form-item>

            </div>
            <el-form-item class="form-group clearfix" prop="date">
              <div class="form-group clearfix">
                <div class="user-info-label">{{ $t('personalInfo.user.date') }}</div>
                <el-date-picker id="birthday-input" class="time-input text-input valid"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="请选择出生如期" v-model="form.birthDate"></el-date-picker>
              </div>
            </el-form-item>
            <div class="form-btn-line">
              <div class="form-btn clearfix">
                <button class="button button-red-solid submit-btn pull-left"
                        style="margin-right: 50px" @click="save('form')">{{ $t('personalInfo.save') }}
                </button>
                <button class="button button-red-hollow submit-btn pull-left"
                        @click="cancelForm">{{ $t('personalInfo.cancel') }}
                </button>
              </div>
            </div>
          </div>
        </el-form>
      </div>


      <el-dialog class="modal-dialog" :title="type === 'phone'? '电话号':'邮箱号'" :visible.sync="dialogFormVisible">
        <el-form name="dialog" class="modal-content" :model="dialog" :rules="rules" ref="dialog">
          <el-form-item :label-width="formLabelWidth" prop="info">
            <div class="pull-left control-name">{{ type === 'phone' ? '电话号' : '邮箱号' }}</div>
            <div class="pull-left control-right">
              <div class="number-wrap">
                <el-input class="text-input phone isPhone" :placeholder="type === 'phone'? '请输入电话号':'请输入邮箱'"
                          v-model="dialog.username" autocomplete="off"></el-input>
              </div>
            </div>

          </el-form-item>
          <el-form-item :label-width="formLabelWidth" prop="captcha">
            <div class="pull-left control-name">验证码</div>
            <div class="pull-left control-right">
              <div class="number-wrap">
                <el-input class="text-input phone isPhone" placeholder="请输入验证码"
                          v-model="dialog.captcha" autocomplete="off"
                          style=" width: 61%!important;"></el-input>
                <el-button class="buttonYan pull-right" :loading="false"
                           :disabled="state.disabled" ref="captcha"
                           @click="captcha('dialog')">{{ state.getCodeText }}
                </el-button>
              </div>
            </div>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button class="button button-red-solid btn-confirm"
                     style="margin-right: 44px;color: #ffffff"
                     @click="confirm('dialog',type)">确定
          </el-button>
          <el-button class="button button-red-hollow" @click="cancel">取消</el-button>
        </div>

      </el-dialog>
    </div>
  </div>
</template>

<script>
import {reactive} from "vue";
import {captchaGet} from "@/apis/common";
import {captchaCheck} from "@/apis/common";
import {updateInfo} from "@/apis/people";
import {getOneInfo} from "@/apis/people";


export default {
  name: "personal",
  data() {
    return {
      loading: true,
      dialogFormVisible: false,
      state: reactive({
        // 获取验证码
        getCodeText: '获取验证码',
        disabled: false,
        holdTime: 60, //默认60秒计时
      }),
      headers: {
        token: localStorage.getItem("token"),
      },
      image: require('../../../../../public/download_doc/common/null_avatar_image.jpg'),
      avatar: '',
      imageUrl: '',
      form: {
        username: '',
        birthDate: '',
        avatar: '',
        phone: '',
        email: '',
        sex: '',
        name: '',
      },
      radio: 1,
      formLabelWidth: '120px',
      dialog: {
        username: '',
        captcha: '',
      },
      type: '',
      rules: {
        username: [
          {required: true, message: '输入框不能为空', trigger: 'blur'},
        ],
        birthDate: [
          {required: true, message: '输入框不能为空', trigger: 'blur'},
        ],


      }
    }
  },

  created() {

    this.init()
  },
  methods: {
    // 页面初始化信息
    async init() {
      this.closeLoading()
      // 获取用户信息
      let id = localStorage.getItem("id")
      // let type = localStorage.getItem("type")
      // UserInfoGet
      getOneInfo(id).then((resp) => {
        if (resp?.data?.code == 1) {
          this.form = resp?.data?.data
          // 头像请求
          this.imageUrl = `/api/common/download?name=${resp?.data?.data?.avatar}`
        } else if (resp?.data?.code == 0) {
          // 获取用户信息失败，说明localStorage中的id存在异常
          // 让用户重新登陆
          this.$message.error("获取用户信息失败，请重新登陆!!")
          this.$router.push({
            name: '/login',
          }).catch(r => {
            console.log(r)
          })
        }
      })

    },

    // 图片上传成功前拦截
    handleAvatarSuccess(res, file) {
      console.log(res)
      this.imageUrl = `/api/common/download?name=${res?.data}`
    },
    // 图片上传前
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },

    // 表单验证
    save(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {

          this.form.avatar = this.imageUrl
          this.form.sex = this.radio == 1 ? '男' : '女'
          updateInfo(this.form).then((resp) => {
            if (resp?.data?.code === 1) {
              this.$message.success("修改信息成功")
              localStorage.setItem("name",this.form.name)
            } else {
              this.$message.error("修改信息失败，请稍后重试!!")
            }
          })

        } else {
          console.log('error submit!!');
          return false;
        }
      });

    },
    // 取消个人信息页面
    cancelForm() {
      let type = localStorage.getItem("type")
      if (type === "student") {
        this.$router.push({
          name: 'studentIndex'
        }).catch(err => {
          console.log(err)
        })
      }
      if (type === "teacher") {
        this.$router.push({
          name: 'teacherIndex',
        }).catch(err => {
          console.log(err)
        })
      }
      if (type === "admin") {
        this.$router.push({
          name: 'adminIndex',
        }).catch(err => {
          console.log(err)
        })
      }

    },

    // 打开对话框
    openDialog(type) {
      this.type = type
      this.dialogFormVisible = true

    },
    // 加载动画
    closeLoading() {
      this.timer = null
      this.timer = setTimeout(() => {
        this.loading = false
      }, 1000)
    },

    // 对话框获取验证码
    captcha(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.state.disabled = true
          this.state.getCodeText = "发送中..." //发送验证码
          // 请求获取验证码
          setTimeout(async () => {
            await captchaGet(this.dialog.username).then((resp) => {
              if (resp?.data?.code === 1) {
                this.$message.success("获取验证码成功===>" + resp?.data?.data)
                this.setTimer(); //调用定时器方法
              } else {
                this.$message.error("获取验证码错误，请稍后重试")
                return false;
              }
            })
          }, 1500)
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

    // 对话框表单验证，验证码验证
    confirm(formName, type) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          captchaCheck(this.dialog.username, this.dialog.captcha).then((resp) => {
            if (resp?.data?.code == 1) {

              this.$message.success("修改信息成功")
              if (type === 'phone') {
                this.form.phone = this.dialog.username
              } else {
                this.form.email = this.dialog.username
              }
              this.dialog.username = ''
              this.dialog.captcha = ''
              this.dialogFormVisible = false
            } else {
              this.$message.error(resp.data.msg)
            }
          })

        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 取消
    cancel() {
      this.dialogFormVisible = false
      this.dialog.username = ''
    },

    // 计时器
    setTimer() {

      let Timer = null;
      Timer = setInterval(() => {
        if (this.state.holdTime <= 0) {
          this.state.disabled = false
          this.state.getCodeText = "获取验证码"
          clearInterval(Timer); //清除该函数
          return;
        }
        this.state.getCodeText = "重新获取(" + this.state.holdTime + ")"
        this.state.holdTime--;
      }, 1000)

    },
  }

}
</script>


<style>

*, :after, :before {
  box-sizing: border-box;
}

div {
  display: block;
}

body, html {
  color: #444;
  font-size: 14px;
}

a {
  background-color: transparent;
  color: #337ab7;
  text-decoration: none;
}


a:active, a:hover {
  outline: 0;
}

</style>
<!-- scoped表示该css的作用范围只在此组件-->
<!--  用::v-deep可以对已有属性进行覆盖-->
<style scoped>
::v-deep .el-form-item__error {
  left: 15%;
}

.divTmp {
  width: 100%;
}

::v-deep .el-loading-mask {
  transition: opacity 0s;
}

::v-deep .el-loading-spinner {
  top: 100%;
  margin-top: 30%;
  width: 100%;
  text-align: center;
  position: absolute;
}

el-upload {
  border: 1px solid red;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.form-wrapper {
  margin: 30px auto;
  padding: 0 20px;
  max-width: 760px;
}

.user-info-title {
  text-align: right;
  margin-bottom: 15px;
  color: #ea5947;
  font-size: 16px;
  font-weight: 700;
  width: 100px;
}

.form-group {
  margin-bottom: 15px;
}

.user-page .user-info-page .form-group {
  margin-bottom: 20px;
  width: 100%;
  min-height: 32px;
  position: relative;
}


.user-page .user-info-page .user-info-label {
  float: left;
  text-align: right;
  margin-right: 20px;
  width: 100px;
  height: 32px;
  line-height: 32px;
}

.user-page .user-info-page .form-group .link-btn,
.user-page .user-info-page .form-group .phone,
.user-page .user-info-page .form-group .user-info-userName {
  height: 30px;
  line-height: 30px;
}

.pull-left {
  float: left !important;
}

.user-page .gray {
  color: #969696;
}


form {
  display: block;
  margin-top: 0em;
}

.user-page .user-info-page .form-group {
  margin-bottom: 20px;
  width: 100%;
  min-height: 32px;
  position: relative;
}


.user-page .user-info-page .user-info-label {
  float: left;
  text-align: right;
  margin-right: 20px;
  width: 100px;
  height: 32px;
  line-height: 32px;
}

.user-page .user-info-page .avatar-area {
  margin-bottom: 18px;
  width: 76%;
}


.user-page .user-info-page .avatar-area .avatar-container {
  margin-right: 10px;
  padding-top: 4px;
  text-align: center;
}


img {
  border: 0;
  vertical-align: middle;
}

.user-page .user-info-page .avatar-area .avatar {
  border-radius: 100%;
  width: 80px;
  height: 80px;
}

.user-page .user-info-page .avatar-area .button {
  margin: 18px 18px 18px -200px;
}

.button-red-solid {
  background-color: #7691fc;
  border-color: #7691fc;
}

.button-red-solid:active {
  background-color: #5c71c3;
  border-color: #5c71c3;
}

.button-red-solid:hover {
  background-color: #90a6fc;
  border-color: #90a6fc;
}

.button {
  padding: 0 10px;
  border-radius: 4px;
  background-color: #ea5947;
  border: 1px solid #ea5947;
  cursor: pointer;
  display: inline-block;
  min-width: 80px;
  height: 32px;
  line-height: 30px;
  font-size: 14px;
  outline: none;
  color: #fff;
  vertical-align: middle;
  font-family: inherit;
  -webkit-appearance: button;
  text-transform: none;
  overflow: visible;

}

.button-red-solid {
  background-color: #ea5947;
  border-color: #ea5947;
  color: #fff;
}

.user-page .user-info-page .tip-text {
  font-size: 12px;
  color: #969696 !important;
}

.user-page .user-info-page .label-right {
  width: 76%;
  line-height: 32px;
}

.user-page .user-info-page .label-right .edit {
  cursor: pointer;
  color: #ea5947;
}

.user-page .user-info-page .user-info-label i {
  margin-right: 10px;
  font-style: normal;
  font-weight: 700;
  color: #ea5947;
}

input {
  margin: 0;
}

.user-page .user-info-page .text-input {
  border-radius: 4px;
  background-color: #fff;
  width: 76%;
  height: 32px;
  font-size: 14px;
  line-height: 32px;
}

.user-page .user-info-page .error-tip {
  margin-left: 120px;
  margin-top: 5px;
  color: #f60000;
  font-size: 14px;
}

p {
  margin: 0 0 10px;
}

.user-page .user-info-page .tip-text {
  font-size: 12px;
  color: #969696 !important;
}


.radio-group {
  padding-left: 0px;
  font-size: 0;
  height: 30px;
  line-height: 30px;

}

.el-radio-group {
  display: block;
}

.user-page .user-info-page .radio-group .radio-item {
  margin-right: 32px;
  cursor: pointer;
  display: inline-block;
}

.el-radio__input {
  text-align: center;
  border-radius: 100%;
  border: 2px solid #ea5947;
}

.el-radio {
  line-height: 2;
}

::v-deep .el-radio:hover {
  border-color: #ffffff;
}

::v-deep .el-radio__inner:hover {
  border-color: #ffffff;
}

::v-deep .el-radio__input.is-checked + .el-radio__label {
  color: #dd1a20 !important;
}

::v-deep .el-radio__input.is-checked .el-radio__inner {
  border-color: #dd1a20;
  background: #ffffff;
  border-radius: 100%;
}

::v-deep .radio-item .el-radio__inner::after {
  width: 6px;
  height: 6px;
  background-color: #dd1a20;
}

.el-input__inner {
  height: 32px;
  line-height: 32px;
}

.el-input__icon {
  line-height: 32px;
}


.user-page .user-info-page .form-btn-line .submit-btn {

  display: block;
}

.button-red-solid {
  background-color: #7691fc;
  border-color: #7691fc;
}

.user-page .user-info-page #form-user .form-btn-line {
  margin: 60px -20px;
  padding-top: 24px;
  border-top: 1px solid #e3e3e9;
}

.user-page .user-info-page .form-btn-line .form-btn {
  width: 212px;
  margin: 0 auto;
  height: 32px;
}

.button-red-hollow {
  background-color: #fff;
  border-color: #e3e3e9;
  color: #7691fc;
}

.button-red-hollow:hover {
  border-color: #5c71c3;
}

.el-form-item__error {
  left: 17%;
}

.user-page .user-info-page .label-right span {
  margin-right: 5px;
}


.user-page .content-container {
  margin: auto;
  background: #fff;
  padding: 0;
}

.container {
  padding-right: 15px;
  padding-left: 15px;
  margin-right: auto;
  margin-left: auto;
}

.user-page .el-image__inner .user-head {
  background-repeat: no-repeat;
  background-position: 50%;
  background-size: auto 100%;
  background-color: #ffecee;
}


.user-page, .user-page .content-container {
  height: 100%;
}

.user-page .el-image__inner .user-head {
  height: 100px;
  width: 100%;
}


.user-page .user-info-page {
  padding: 20px;
  background-color: #fff;
}

.user-page .user-info-page {
  position: relative;
}

.user-page .user-info-page .user-info-page-menu {
  text-align: center;
  border: 1px solid #ea5947;
  margin: 12px auto 0;
  border-radius: 4px;
}


.user-page .user-info-page .user-info-page-menu .active {
  background: #ea5947;
  color: #fff;
}

.user-page .user-info-page .user-info-page-menu {
  height: 34px;
  width: -moz-fit-content;
  width: fit-content;
  line-height: 32px;
}


.user-page .user-info-page .user-info-page-menu .user-info-page-nav {
  float: left;
  border-right: 1px solid #ea5947;
}

.user-page .user-info-page .user-info-page-menu .user-info-page-nav {
  padding: 0 10px;
  text-align: center;
  color: #ea5947;
}

.user-page .user-info-page .user-info-page-menu a:focus, .user-page .user-info-page .user-info-page-menu a:hover {
  text-decoration: none;
}

.user-page .user-info-page .user-info-page-menu .active {
  color: #fff;
}


::v-deep .el-dialog {
  width: 480px;
  transform: translateY(50%);
  border: 1px solid #999;
  border-radius: 6px;

}


::v-deep .el-dialog__header {
  padding: 0 24px;
  border: none;
  background: url(../../../../assets/common/popup_top_bg.png) #ea5947 no-repeat 50%;
  background-size: 100% 100%;
  height: 42px;
  color: #fff;
}

::v-deep .el-dialog__title {
  margin: 0;
  font-size: 16px;
  line-height: 42px;
  color: #ffffff;
}

::v-deep .el-dialog__headerbtn {
  top: 13px;
}

::v-deep .el-dialog__headerbtn .el-dialog__close {
  font-weight: 400;
  color: #fff;
  opacity: .8;
}

::v-deep .el-dialog__body {
  padding: 30px 28px 0;
}

::v-deep .el-form-item {
  margin-bottom: 30px;
}

::v-deep .el-form-item__content {
  margin-left: 0 !important;
}

.control-name {
  padding-right: 20px;
}

.control-right {
  width: 85%;
}

.number-wrap {
  position: relative;
}

.phone {
  width: 100% !important;
}

::v-deep .el-input__inner {
  height: 40px !important;
  line-height: 40px !important;
}

.pull-right {
  float: right !important;
}

.buttonYan {
  border-radius: 4px;
  background-color: #ea5947;
  height: 40px;
  width: 33%;
  color: #fff;
  border: 1px solid #ea5947;
}

.buttonYan:hover {
  background-color: #ee7a6c;
  border-color: #ee7a6c;
}

::v-deep .el-dialog__footer {
  padding: 14px 24px;
  text-align: center;
  border: none;
  background-color: #efeff7;
}

.button-red-solid {
  background-color: #7691fc;
  border-color: #7691fc;
}


</style>